<template>
  <a-card :bordered="false">
    <h3>门店组列表</h3>
    <LessFilter ref="filter" :type="4" @onAdd="handleAddOrEdit" @onExport="handleTemplate" @onSearch="onSearch"></LessFilter>

    <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }">
      <span slot="action" slot-scope="record">
        <a-button class="btn" style="min-width: 90px;" @click="handleShow(record)">查看</a-button>
        <a-button class="btn" style="min-width: 90px;" @click="handleAddOrEdit(record)">编辑</a-button>
        <a-popconfirm title="确定删除门店组吗？" ok-text="确定" cancel-text="暂不" @confirm="handleDelete(record)">
          <a-button class="btn" style="min-width: 90px;">删除</a-button>
        </a-popconfirm>
      </span>
    </s-table>

    <a-modal :title="(eidt ? '编辑' : '新增') + '门店组'" :visible="visible" width="800px" @ok="modelFormOk" @cancel="visible = false">
      <a-spin :spinning="spinning" tip="加载中...">
        <a-form-model ref="storeForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 4 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }">
          <a-form-model-item label="门店组名" prop="groupName">
            <a-input allowClear v-model.trim="form.groupName" :maxLength="16" placeholder="最多输入16字"/>
          </a-form-model-item>
          <a-form-model-item label="门店">

            <a-upload
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              name="file"
              :showUploadList="false"
              :multiple="false"
              :data="uploadData"
              :action="uploadUrl"
              @change="handleChange"
            >
              <a-button type="primary" style="margin-left: 15px;">导入门店</a-button>
            </a-upload>
            多次导入门店，以最后一次导入数据为准
            <a-table :pagination="storePagination" bordered :columns="storeColumns" :data-source="form.stores"
                     :rowKey="(record, index) => index" size="middle" @change="handleStoreChange">
                        <span slot="action" slot-scope="text, record, index">
                          <a-popconfirm title="请确认是否删除？" @confirm="handleDeletStore(record.id)">
                            <a>删除</a>
                          </a-popconfirm>
                        </span>
            </a-table>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>

    <a-modal title="查看门店组" :visible="showVisible" width="800px" :footer="null" @cancel="showVisible = false">
      <a-form-item label="门店组名">
        {{form.groupName}}
      </a-form-item>
      <a-form-item label="门店">
        <a-table :pagination="storePagination" bordered :columns="showColumns" :data-source="form.stores"
                 :rowKey="(record, index) => index" size="middle" @change="handleStoreChange">
        </a-table>
      </a-form-item>y
    </a-modal>
  </a-card>
</template>
<script>
  import moment from 'moment'
import { storeGroupList, storeTemplateDonwload, importStore, saveOrUpdateStore, storeGroupDetail, removeStoreGroup } from '@/api/marketingCenter/less'
import { STable } from '@/views/box/components'
import LessFilter from '../components/lessFilter'
  import AFormModelItem from 'ant-design-vue/es/form-model/FormItem'
  import AFormItem from 'ant-design-vue/es/form/FormItem'

export default {
  components: {
    AFormItem,
    AFormModelItem,
    LessFilter,
    STable
  },
  data() {
    return {
      visible: false,
      showVisible: false,
      eidt: false,
      spinning: false,
      columns: [
        {
          title: '门店组名',
          align: 'center',
          dataIndex: 'groupName'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align:"center",
          customRender: (text) => {
            return moment(text).format('YYYY-MM-DD')
          }
        },
        {
          title: '操作',
          width: '350px',
          align: 'center',
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      storeColumns: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'storeCode'
        },
        {
          title: '门店名',
          dataIndex: 'storeName',
          align:"center"
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          align:"center"
        },
        {
          title: '操作',
          width: '1',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      showColumns: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'storeCode'
        },
        {
          title: '门店名',
          dataIndex: 'storeName',
          align:"center"
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          align:"center"
        }
      ],
      storePagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {
        "groupName": "",
        "storeName": ""
      },

      form: {
        id: 0,
        groupName: '',
        stores: []
      },

      uploadData: {
      },
      uploadUrl: importStore,
      rules: {
        groupName: [{ required: true, message: '请输入', trigger: 'blur' }]
      },

      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
        const data = {
          "current": parameter.pageNo,
          "size": parameter.pageSize,
          ...this.queryParam
        }
        return storeGroupList(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  activated() {
  },
  computed: {},
  mounted() {},
  watch: {
  },
  methods: {
    requestFlag() {
      const currentPathBase = '/marketingCenter/less/store/storeGroupList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    // 删除
    handleDelete(record) {
      removeStoreGroup({id: record.id}).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },
    handleShow(v) {
      storeGroupDetail({id: v.id}).then(res => {
        if (res.code === 200) {
          this.form.id = res.data.id;
          this.form.groupName = res.data.groupName;
          this.form.stores = res.data.stores;
          this.showVisible = true;
        } else {
          this.$message.error(res.msg || res.message)
        }
      }).catch(err => {
      })
    },

    // 新增编辑
    handleAddOrEdit(v) {
      if(v != 'null'){
        storeGroupDetail({id: v.id}).then(res => {
          if (res.code === 200) {
            this.form.id = res.data.id;
            this.form.groupName = res.data.groupName;
            this.form.stores = res.data.stores;
            this.visible = true;
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
        })
      }else{
        this.form.id = 0;
        this.form.groupName = '';
        this.form.stores = [];
        this.visible = true;
      }
    },
    // 下载门店导入模版
    handleTemplate() {
      window.location.href = storeTemplateDonwload
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },

    modelFormOk() {
      this.$refs.storeForm.validate(valid => {
        if (valid) {
          if (!this.form.stores.length) {
            this.$message.error('请上传门店！')
            return
          }
          const data = {
            ...this.form
          }
          this.spinning = true
          saveOrUpdateStore(data).then(res => {
            if (res.code === 200) {
              this.spinning = false
              this.visible = false
              this.$refs.table.refresh(true)
            } else {
              this.spinning = false
              this.$message.error(res.msg || res.message)
            }
          }).catch(err => {
            this.spinning = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    handleStoreChange(pagination) {
      const pager = { ...this.storePagination }
      pager.current = pagination.current
      this.storePagination = pager
      // this.getluckyDrawStoreList()
    },

    // 删除指定门店
    handleDeletStore(id){
      const index = this.form.stores.findIndex((e) => e.id == id);
      this.form.stores.splice(index, 1)
    },
    // 导入指定门店
    handleChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        const {msg, message, code, data} = info.file.response
        if (code == 200 ) {
          this.form.stores = data
        } else {
          this.$message.error(msg || message)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img {
  display: block;
  margin: 0 auto;
  width: 120px;
  height: 120px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
}
.btn{
  margin: 4px;
}
</style>
